package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersStatusAllDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.LocationUtils;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.HasAnnotation;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import static com.sky.entity.Orders.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yangkexuan
 * @className OrderServicelmpl
 * @date 2023/6/13 14:07
 * @description
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private LocationUtils locationUtils;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 最远配送距离
     */
    private static final int MAXIMUM_DELIVERY_DISTANCE= 5000;
    /**
     * 用户下单
     * @return OrderSubmitVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //异常情况处理：收货地址为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //超出配送范围
        StringBuilder sb = new StringBuilder();
        sb.append(addressBook.getProvinceName())
                .append(addressBook.getCityName())
                .append(addressBook.getDistrictName())
                .append(addressBook.getDetail());

        String addressUser = sb.toString();
        Double res = null;
        try {
            res = locationUtils.getResult(addressUser);
            log.info("两地距离为：{}",res);
        } catch (Exception e) {
            log.error("两地距离计算错误");
            e.printStackTrace();
        }
        //如果超出5KM
        if(res > MAXIMUM_DELIVERY_DISTANCE){
            throw new AddressBookBusinessException(MessageConstant.EXCEED_MAXIMUM_DELIVERY_DISTANCE);
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        //购物车为空
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone())
                .setAddress(addressBook.getDetail())
                .setConsignee(addressBook.getConsignee())
                .setNumber(String.valueOf(System.currentTimeMillis()))
                .setUserId(userId)
                .setStatus(Orders.PENDING_PAYMENT)
                .setPayStatus(Orders.UN_PAID)
                .setOrderTime(LocalDateTime.now());

        //插入数据
        orderMapper.insert(order);

        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }
        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);
        //清空购物车数据
        shoppingCartMapper.deleteByUserId(userId);
        //封装返回结果
        return OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();
    }

    /**
     * 历史订单查询 分页查询
     * @param ordersPageQueryDTO
     * @return PageResult
     */
    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        //根据订单ID查询
        Orders ordersAll = new Orders();
        BeanUtils.copyProperties(ordersPageQueryDTO,ordersAll);
        ordersAll.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> dishList = (Page<Orders>) orderMapper.selectList(ordersAll);

        List<OrderVO> list = new ArrayList<>();
        //查询订单明细，并封装
        if(dishList != null && dishList.getTotal() > 0){
            for (Orders orders : dishList) {
                Long ordersId = orders.getId();
                // 查询订单明细
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(ordersId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                orderVO.setOrderDetailList(orderDetailList);

                //将订单菜品名称以字符串形式展示
                String orderInfo = orderDetailMapper.getNameByOrderId(orders.getId());
                orderVO.setOrderDishes(orderInfo);
                list.add(orderVO);
            }
        }
        return new PageResult(dishList.getTotal(), list);
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO selectOrderDetailById(Long id) {
        Orders orders = orderMapper.selectListById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 修改订单状态
     * @param ordersStatusAllDTO
     */
    @Override
    public void updateCancelOrder(OrdersStatusAllDTO ordersStatusAllDTO) {
        //如果为取消订单，则多加一个判断判断订单状态，为 1. 2.2 3. 4. 时可以取消
        if(ordersStatusAllDTO.getStatus().equals(COMPLETED)){
            Integer num = orderMapper.selectOrderStatus(ordersStatusAllDTO.getId());
            if (num == 0){
                throw new AddressBookBusinessException(MessageConstant.NO_CANCELLATION_ORDER);
            }
        }
        orderMapper.updateCancelOrder(ordersStatusAllDTO);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO selectStatistics() {
        return orderMapper.selectStatistics(null,null);
    }

    /**
     * 支付成功，修改订单状态
     * @param ordersPaymentDTO
     */
    @Override
    public void paySuccess(OrdersPaymentDTO ordersPaymentDTO){
        //当前登录用户id
        Long userId = BaseContext.getCurrentId();
        //根据订单号查询当前用户的订单
        Orders orders = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(),userId);

        //根据订单id更新订单的状态，支付方式，支付状态，结账状态

        Orders ordersUpdate = Orders.builder()
                .id(orders.getId())
                .status(TO_BE_CONFIRMED)
                .payMethod(PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(ordersUpdate);

        //更新消息提醒
        Map map = new HashMap(10);
        // 消息类型： 1表示来单提醒
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号：" + ordersPaymentDTO.getOrderNumber());

        //通过WebSocket发送提醒
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 催单
     * @param id
     */
    @Override
    public void ReminderUser(Long id) {
        //通过订单ID查询订单号
        Orders orders = orderMapper.selectListById(id);

        Map map = new HashMap(10);
        // 2 催单
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号：" + orders.getNumber());

        //通过WebSocket发送提醒
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }
}
